/**
 * Created by DengYun on 2017/2/25.
 */

import React from 'react';
import { Table } from 'antd';
import { observer } from 'mobx-react';
import { observable, action, runInAction } from 'mobx';

let tokenCounter = 0;

@observer
export default class PageList extends React.Component {
  pagination = observable({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  @observable
  loading = true;

  @observable
  data = [];

  componentDidMount() {
    this.fetchData();
  }

  async fetchData() {
    const { fetchData } = this.props;
    const token = this.fetchToken = tokenCounter++;
    this.loading = true;
    const { content, count } = await fetchData(this.pagination.current, this.pagination.pageSize);
    if (token === this.fetchToken) {
      runInAction(() => {
        this.pagination.total = count;
        this.data.replace(content);
        this.loading = false;
      });
    }
  }

  @action
  onChange = (pagination, filters, sorter) => {
    this.pagination.current = pagination.current;
    this.pagination.pageSize = pagination.pageSize;
    this.fetchData();
  }

  render() {
    return (
      <Table
        columns={this.props.columns}
        pagination={this.pagination}
        dataSource={this.data.slice(0)}
        onChange={this.onChange}
        loading={this.loading}
        />
    )
  }
}
